package com.code.soulqlexpress.func;

import com.ql.util.express.Operator;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yzh
 * @date 2020/4/30
 * @content 排除null, 求最大值最小值
 */
public class MyMinMaxOperator extends Operator {

    public MyMinMaxOperator(String name) {
        this.name = name;
    }

    private static final String MIN = "mymin";

    private static final String MAX = "mymax";

    @Override
    public Object executeInner(Object[] list) throws Exception {
        if (list.length == 0) {
            throw new Exception("操作数异常");
        }
        List<Object> notNullList = new ArrayList<Object>();
        for (int i = 0; i < list.length; i++) {
            Object obj = list[i];
            if (null == obj) {
                continue;
            }
            notNullList.add(obj);
        }
        if (CollectionUtils.isEmpty(notNullList)) {
            return null;
        }
        Object result = notNullList.get(0);
        for (int i = 1; i < notNullList.size(); i++) {
            result = executeInner(result, notNullList.get(i));
        }
        return result;
    }

    private Object executeInner(Object op1, Object op2) throws Exception {
        Object result = null;
        int compareResult = Operator.compareData(op1, op2);
        if (this.name.equals(MIN)) {
            if (compareResult < 0) {
                result = op1;
            } else {
                result = op2;
            }
        } else if (this.name.equals(MAX)) {
            if (compareResult < 0) {
                result = op2;
            } else {
                result = op1;
            }
        }
        return result;
    }
}
